<!-- 个人中心 -->
<template>
  <div class="wrapper">
    <div class="block-header">
      <n-space align="center">
        <div class="title">部门管理:</div>
        <n-button
          @click="handleCreate"
          size="small"
          type="primary"
          secondary
          strong
          >{{ $t("add department") }}</n-button
        >
        <n-divider vertical></n-divider>

        <!-- <n-select
          size="small"
          style="width: 180px"
          :options="sortOptions"
          v-model:value="searchParams.sort"
        ></n-select> -->
      </n-space>
      <n-space style="margin-left: auto">
        <!-- <n-input
          style="width: 150px"
          size="small"
          :placeholder="$t('please input keyword')"
        >
          <template #prefix>
            <n-icon :component="SearchOutline" />
          </template>
        </n-input>
        <n-button size="small" type="primary" secondary strong>{{
          $t("new form")
        }}</n-button> -->
      </n-space>
    </div>

    <n-divider></n-divider>

    <div class="container">
      <div class="left">
        <n-tree
          block-line
          :data="departmentTree"
          :default-expanded-keys="defaultExpandedKeys"
          expand-on-click
          :node-props="nodeProps"
        />
      </div>
      <n-divider style="height: 800px" vertical></n-divider>
      <div class="right">
        <n-space align="center">
          <n-button @click="handleCreateUser" type="primary" secondary
            >添加用户</n-button
          >
        </n-space>
        <n-divider style="margin: 12px 0"></n-divider>
        <n-data-table
          :rowKey="(row) => row.id"
          :columns="columns"
          :data="userList"
          :pagination="pagination"
        ></n-data-table>
      </div>
    </div>
    <formBuilder
      @submit="handleConfirm"
      ref="Upsert"
      :schema="departmentSchema"
    ></formBuilder>
    <formBuilder
      @submit="handleConfirm"
      ref="userUpsert"
      :schema="userSchema"
    ></formBuilder>
    <n-dropdown
      trigger="manual"
      placement="bottom-start"
      :show="showDropdown"
      :options="(optionsRef as any)"
      :x="xRef"
      :y="yRef"
      @select="handleSelect"
      @clickoutside="handleClickoutside"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, h } from "vue";
import centerFrame from "../components/storage/components/centerFrame.vue";
import { useRouter } from "vue-router";
import {
  SearchOutline,
  EllipsisVerticalOutline,
  DocumentTextOutline,
  ChevronBackOutline,
} from "@vicons/ionicons5";
import {
  addUser,
  deleteUser,
  getFormUsers,
  getUserDetail,
  moveDepartment,
  updateUser,
} from "@/api/user";
import {
  DropdownOption,
  NAvatar,
  NButton,
  NSpace,
  NSwitch,
  NTag,
  NTreeSelect,
  TreeOption,
} from "naive-ui";
import departmentSchema from "@/json/department.json";
import userSchema from "@/json/userForm.json";
import formBuilder from "@/components/form-builder/dialog.vue";
import { useMessage, useDialog, useModal } from "naive-ui";
import { addDepartment, departmentList } from "@/api/department";
import { deepTree } from "@/utils";
const message = useMessage();
const dialog = useDialog();
const Upsert = ref();
const userUpsert = ref();
const pagination = ref({ pageSize: 10, page: 1 });
const userList = ref([]);
const router = useRouter();
const modal = useModal();
const showDropdownRef = ref(false);
const showDropdown = showDropdownRef;
const optionsRef = ref<DropdownOption[]>([
  { label: "添加子部门", value: 0, key: 0 },
  { label: "删除", value: 1, key: 1 },
]);
const xRef = ref(0);
const yRef = ref(0);
const selectOption = ref<any>({});
const selectDepartmentId = ref(-1);
const searchParams = {
  role: "",
  username: "",
};
const handleSelect = (index: number) => {
  // console.log(e);
  if (index == 0) {
    handleCreate(selectOption.value.label, selectOption.value.key);
  } else if (index == 1) {
    dialog.error({
      title: "删除",
      content: `确认删除部门${selectOption.value.label}?`,
      positiveText: "确认删除",
      negativeText: "取消",
      onPositiveClick() {},
    });
  }
  showDropdownRef.value = false;
};
const handleClickoutside = () => {
  showDropdownRef.value = false;
};
const deepGetKeys = (item) => {
  const res = [];
  if (!item) {
    return res;
  }
  res.push(item.key);
  if (item.children) {
    for (let i = 0; i < item.children.length; i++) {
      res.push(...deepGetKeys(item.children[i]));
    }
    // res.push(...deepGetKeys())
  }
  return res;
};
const nodeProps = ({ option }: { option: TreeOption }) => {
  return {
    onClick() {
      selectOption.value = option;
      selectDepartmentIds.value = deepGetKeys(option);

      console.log(option, selectDepartmentIds.value);
      loadData();
      // message.info("[Click] " + option.label);
    },
    onContextmenu(e: MouseEvent): void {
      selectOption.value = option;
      console.log(option);
      // optionsRef.value = [option];
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log(e.clientX, e.clientY);
      e.preventDefault();
    },
  };
};
const defaultExpandedKeys = ref([]);
// const options = ref([
//   {
//     label: "数据管理",
//     value: "数据管理",
//   },
//   {
//     label: "问卷填写",
//     value: "问卷填写",
//   },
// ]);
const handleBack = () => {
  router.back();
};
const columns = [
  {
    type: "selection",
    fixed: "left",
  },
  {
    title: "头像",
    key: "headImg",
    render(row) {
      return h(NAvatar, { src: row.headImg });
    },
  },
  {
    title: "用户名",
    key: "username",
  },
  {
    title: "昵称",
    key: "nickName",
  },
  {
    title: "角色",
    key: "roleName",
    render(row) {
      return h(
        NSpace,
        { align: "center" },
        {
          default: () =>
            row.roleName
              .split(",")
              .map((item) =>
                h(
                  NTag,
                  { size: "small", type: "primary" },
                  { default: () => item }
                )
              ),
        }
      );
    },
  },
  {
    title: "邮箱",
    key: "email",
    render: (row) => {
      return row.email || "暂无";
    },
  },
  {
    title: "状态",
    key: "status",
    render(row) {
      return h(NSwitch, {
        value: row.status,
        uncheckedValue: 0,
        checkedValue: 1,
      });
    },
  },
  {
    title: "操作",
    key: "actions",
    fixed: "right",
    render(row) {
      return h(
        NSpace,
        { align: "center" },
        {
          default: () => [
            h(
              NButton,
              {
                strong: true,
                secondary: true,
                type: "error",
                size: "small",
                onClick() {
                  dialog.error({
                    title: "删除用户",
                    content: "你确定要删除用户吗？",
                    positiveText: "确认",
                    negativeText: "取消",
                    onPositiveClick(e) {
                      deleteUser({ ids: [row.id] })
                        .then((res) => {
                          message.success("删除成功");
                          loadData();
                        })
                        .catch((e) => {
                          message.error(`删除失败:${e}`);
                        });
                    },
                  });
                },
              },
              { default: () => "删除" }
            ),
            h(
              NButton,
              {
                strong: true,
                secondary: true,
                type: "success",
                size: "small",
                onClick() {
                  handleEditUser(row.id);
                },
              },
              { default: () => "编辑" }
            ),
            h(
              NButton,
              {
                strong: true,
                secondary: true,
                type: "warning",
                size: "small",
                onClick() {
                  modal.create({
                    title: "转移部门",
                    content: () =>
                      h(NTreeSelect, {
                        options: departmentTree.value,
                        defaultExpandAll: true,
                        onUpdateValue(e) {
                          selectDepartmentId.value = e;
                          console.log(e);
                        },
                      }),
                    preset: "dialog",
                    positiveText: "确认",
                    negativeText: "取消",
                    onPositiveClick() {
                      moveDepartment({
                        userIds: [row.id],
                        departmentId: selectDepartmentId.value,
                      })
                        .then((res) => {
                          message.success("转移成功");
                          loadData();
                        })
                        .catch((e) => {
                          message.error(`转移失败:${e}`);
                        });
                    },
                  });
                  // handleEditUser(row.id);
                },
              },
              { default: () => "转移" }
            ),
          ],
        }
      );
    },
  },
];
const selectDepartmentIds = ref([]);
const departmentTree = ref([]);
const handleCreate = (parentName = "", parentId = 0) => {
  Upsert.value.open({ title: "创建部门", data: { parentId, parentName } });
};
const handleCreateUser = () => {
  if (!selectOption.value.key) {
    message.error("请先选中左边的部门");
    return;
  }
  console.log(selectOption.value.label);
  userUpsert.value.open({
    title: "创建用户",
    data: {
      departmentId: selectOption.value.key,
      departmentName: selectOption.value.label,
    },
  });
};
const handleEditUser = (id: number) => {
  getUserDetail({ id }).then((res) => {
    console.log(res);
    userUpsert.value.open({ title: "修改用户", data: res["data"] });
  });
  // Upsert.value
};
const handleConfirm = ({ title, data }) => {
  console.log(title, data);
  if (title == "修改用户") {
    updateUser(data)
      .then((res) => {
        loadData();
        message.success("修改成功");
      })
      .catch((e) => {
        message.error("修改失败");
      });
  } else if (title == "创建部门") {
    if (!data["parentId"]) {
      data["parentId"] = 1;
    }
    addDepartment(data)
      .then((res) => {
        loadData();
        message.success("添加成功");
        getDepartmentList();
      })
      .catch((e) => {
        message.error("添加失败");
      });
  } else if (title == "创建用户") {
    addUser(data)
      .then((res) => {
        loadData();
        message.success("添加成功");
        loadData();
      })
      .catch((e) => {
        message.error(`添加失败：${e}`);
      });
  }
};
const deepMap = (item: any) => {
  if (item) {
    // return tree.children.map((item) => {
    //   return {
    //     label: item.name,
    //     key: item.id,
    //     children: deepMap(item),
    //   };
    // });
    return {
      label: item.name,
      key: item.id,
      children: item.children?.map((subItem) => deepMap(subItem)),
    };
  }
};
const getDepartmentList = () => {
  departmentList({}).then((res: any) => {
    console.log(res);
    const convertData = deepTree(res.data);
    console.log(convertData);
    departmentTree.value = deepMap(convertData[0]).children;
    if (convertData[0].children.length > 0) {
      // defaultExpandedKeys.value = convertData[0].children[0].id;
    }
  });
};
const loadData = () => {
  getFormUsers({
    ...pagination.value,
    departmentIds: selectDepartmentIds.value,
  }).then((res: any) => {
    console.log(res);
    userList.value = res.data.list;
  });
};
onMounted(() => {
  getDepartmentList();
  loadData();
});
</script>

<style lang="scss" scoped>
.block-header {
  display: flex;
  align-items: center;
  .title {
    font-weight: bold;
    font-size: 24px;
  }
}
.row {
  display: flex;
  align-items: center;
  .row-label {
    font-weight: bold;
    margin-right: 12px;
  }
}
.container {
  display: flex;
  text-align: left;
  .left {
    width: 250px;
  }
  .right {
    flex: 1;
  }
}
</style>
